import java.util.Arrays;
import java.util.Collections;

public class Leet31 {
    public static void main(String[] args) {
        Leet31 l = new Leet31();
        l.nextPermutation(new int[]{3,2,1});
    }
    public void nextPermutation(int[] nums) {
        if (nums.length==1)
            return;
        int tar = Integer.MIN_VALUE;
        int i;
        for (i = nums.length-1; i>0; i--) {
            if (nums[i]>nums[i-1]){
                tar = nums[i];
                break;
            }
        }
        i--;
        if (tar == Integer.MIN_VALUE){
            int[] re = new int[nums.length];
            for (int i1 = 0; i1 < nums.length; i1++)
                re[i1] = nums[nums.length-i1-1];
            System.arraycopy(re, 0, nums, 0, re.length);
            return;
        }
        int t = Integer.MAX_VALUE,jj = 0;
        for (int j = i+1; j < nums.length; j++)
            if (nums[j]>nums[i]&&nums[j]<t){
                t = nums[j];
                jj = j;
            }
        int a = nums[i];
        nums[i]= nums[jj];
        nums[jj] = a;
        Arrays.sort(nums,i+1,nums.length);
    }
}
